package com.example.module_mine.widget

import android.content.Context
import android.text.Editable
import android.text.TextWatcher
import android.util.AttributeSet
import android.util.Log
import android.view.LayoutInflater
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.FrameLayout
import com.example.module_mine.R

/**
 * @author yaotianxue
 * @description
 * @date 2025/2/8
 */
class VerifyCodeView: FrameLayout {

    private val codeViewList:List<VerifyCodeItemView> //验证码view
    private val et:EditText //编辑框


    private var codeLength = 0 //验证码长度
    private var inputText = "" //输入的验证码
    private var onInputVerifyCodeViewCompleted:((smsCode:String)->Unit)? = null //输入完毕回调

    fun setOnInputVerifyCodeViewCompleted(onInputVerifyCodeViewCompleted:((smsCode:String)->Unit)){
        this.onInputVerifyCodeViewCompleted = onInputVerifyCodeViewCompleted
    }



    constructor(context: Context):this(context,null)
    constructor(context: Context, attrs: AttributeSet?):this(context,attrs,0) //
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr:Int):super(context,attrs,defStyleAttr){
        val view = LayoutInflater.from(context).inflate(R.layout.layout_verify_code_view,this)
        codeViewList = listOf(
            view.findViewById(R.id.code_1)
            ,view.findViewById(R.id.code_2)
            ,view.findViewById(R.id.code_3)
            ,view.findViewById(R.id.code_4)
            ,view.findViewById(R.id.code_5)
            ,view.findViewById(R.id.code_6)
        )
        et = view.findViewById(R.id.et_input)

        codeLength = codeViewList.size
        //设置点击弹出键盘
        view.setOnClickListener {
            showSoftKeyBroad()
        }
        //监听编辑框的内容
        et.addTextChangedListener(EditTextWatcher())
        //监听软键盘的done事件
        et.setOnEditorActionListener { v, actionId, event ->
            if(actionId == EditorInfo.IME_ACTION_DONE){
                hideSoftKeyBroad()
                onInputVerifyCodeViewCompleted?.invoke(inputText)
            }
            true
        }
    }

    /**
     * 弹出键盘
     */
    fun showSoftKeyBroad(){
        val manager:InputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        postDelayed({
            et.requestFocus()
            manager.showSoftInput(et,InputMethodManager.RESULT_UNCHANGED_SHOWN)
        },300)
    }

    /**
     * 隐藏键盘
     */
    fun hideSoftKeyBroad(){
        et.clearFocus()
        val manager:InputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        manager.hideSoftInputFromWindow(et.windowToken,0)
    }

    inner class EditTextWatcher: TextWatcher {
        override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {

        }

        override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
            //获得当前编辑框的内容
            inputText = s.toString()
            Log.d("TAG", "onTextChanged: start=$start, before=$before, count=$count")
            if (before == 0) {
                //焦点前移
                if (inputText.length < codeViewList.size)
                    codeViewList[inputText.length].setFocus(true)
                //取消后位的焦点
                if (inputText.isNotEmpty()) {
                    codeViewList[inputText.length - count].setFocus(false)
                }
                //设置输入的内容
                repeat(inputText.length) {
                    codeViewList[it].setNumber(inputText[it].toString())
                }
            } else {//输入操作
                //焦点后移
                if (inputText.length >= 6) return
                codeViewList[inputText.length].setFocus(true)
                //取消前一位焦点
                if (inputText.length + before < codeViewList.size) {
                    codeViewList[inputText.length + before].setFocus(false)
                }
                //清除输入内容
                repeat(before) {
                    codeViewList[inputText.length + it].setNumber("")
                }
            }

            //输入完毕回调
            if(inputText.length == codeLength){
                hideSoftKeyBroad()
                onInputVerifyCodeViewCompleted?.invoke(inputText)
            }


        }

        override fun afterTextChanged(s: Editable?) {

        }
    }
}